package tokenizer;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;

import Logger.StompLogger;

public class StompTokenizer implements Tokenizer
{

    public final char _delimiter;
    private final InputStreamReader _isr;
    private boolean _closed;

    /**
     * Instantiates a new stomp tokenizer.
     *
     * @param isr the isr
     * @param delimiter the delimiter
     */
    public StompTokenizer (InputStreamReader isr, char delimiter)
    {
    	this._delimiter = delimiter;
    	this._isr = isr;
    	this._closed = false;
    }

    /**
     * Next token.
     *
     * @return the string
     *
     * @throws IOException Signals that an I/O exception has occurred.
     *
     * @see tokenizer.Tokenizer#nextToken()
     */
    public String nextToken() throws IOException
    {
        if (!this.isAlive())
        {
        	StompLogger.write(Level.INFO,"IOException has accured tokenizer is closed");
        	throw new IOException("tokenizer is closed");
        }

        String ans = null;
        try
        {
            // we are using a blocking stream, so we should always end up
            // with a message, or with an exception indicating an error in
            // the connection.
            int c;
            StringBuilder sb = new StringBuilder();
            // read char by char, until encountering the framing character, or
            // the connection is closed.
            while ((c = this._isr.read()) != -1)
            {
                if (c == this._delimiter)
                {
                	break;
                }
                else
                {
                	sb.append((char) c);
                }
            }
            ans = sb.toString();
        }
        catch (IOException e)
        {
            this._closed = true;
            StompLogger.write(Level.INFO,"IOException has accured connection is dead");
            throw new IOException("Connection is dead");
        }
        return ans;
    }

    /**
     * Checks if is alive.
     *
     * @return true, if checks if is alive
     *
     * @see tokenizer.Tokenizer#isAlive()
     */
    public boolean isAlive()
    {
        return !this._closed;
    }

}